var enableBackground = function () {
    var GG_SITES = localStorage.getItem('GG_SITES').split(/\$,\$/) || [];
        sitesLen = GG_SITES.length,

        callback = function  (details) {
            var rndNum = Math.floor( Math.random() * sitesLen +1 ) -1,
                rndUrl = GG_SITES[ rndNum ],
                pairs = Utils.parseQueryString(details.url),
                keyword = pairs.q || '';
           
            return {
                redirectUrl : rndUrl + keyword
            };

        };

    chrome.webRequest.onBeforeRequest.addListener(
        callback,
        {urls: [
            "*://*.google.com/search*",
            "*://*.google.com.hk/search*"]},
        ["blocking"]
    );
};

/**
 * 等declarativeWebRequest正式发布后使用函数
 * 
 * @return {[type]} [description]
 */
var enableBackgroundEvents = function(){

};

chrome.runtime.onInstalled.addListener(function(ExtensionInfo) {
    // localStorage["version"]=APPCFG['version'];
});

var mainfest = chrome.runtime.getManifest(),
    persistent = mainfest.background.persistent === undefined ? false : true;
if (persistent) {
    Utils.getJSON({
        url : 'https://git.oschina.net/dong2590/freegg/raw/master/iplist.json',
        success : function(res) {
            var result = JSON.parse(res.responseText);
            if (result.success) {
                GG_SITES = result.list;
                localStorage.setItem('GG_SITES',GG_SITES.join('$,$'));
                enableBackground();    
            }
        }
    });
    
} else {
    enableBackgroundEvents();
}